<template>
  <div class="continue">
  <div class="left-panel">
    <div class="search-wrapper">
      <div class="input-wrapper">
        <i class="iconfont chat-search"></i>
        <input placeholder="搜索"/>
      </div>
      <div class="add-wrapper" @click="changeFriendStatus(true)">
        <i class="iconfont chat-plus"></i>
      </div>
    </div>
    <div class="message-wrapper">
      <div class="message-item" v-for="item in messageStore.getHistoryList"
           :class="item.f_uuid === messageStore.getActiveFUuid ? 'active' : ''"
           @click="messageStore.setActiveFUuid(item.f_uuid)">
        <div class="avatar">
          <div class="img-wrapper">
            <img
                :src="friendListObj[item.f_uuid].headimgurl?
          friendListObj[item.f_uuid].headimgurl:
          '/src/assets/images/avatar.jpg'">
          </div>
          <div class="unread-wrapper" v-if="item.unread_num">
            {{ item.unread_num > 99 ? 99 : item.unread_num }}
          </div>
        </div>
        <div class="content">
          <div class="head">
            <div class="nickname">{{ friendListObj[item.f_uuid].username }}</div>
            <div class="time">{{ formatDate('m/d', item.created_at) }}</div>
          </div>
          <div class="footer">
            <div class="message">{{ item.msg_view }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
    <div class="right-panel" v-if="messageStore.getActiveFUuid">
    <div class="head-wrapper">
      <div class="nickname">干干</div>
      <div class="tools">
        <div class="menu-list">
          <i class="iconfont chat-pushpin"></i>
          <i class="iconfont chat-minus"></i>
          <i class="iconfont chat-border"></i>
          <i class="iconfont chat-close"></i>
        </div>
        <div class="more">
          <i class="iconfont chat-ellipsis"></i>
        </div>
      </div>
    </div>
      <div ref="detailsRef" @scroll="handleScroll" class="msg-content-wrapper">
      <div class="item item-text"
           v-for="item in messageStore.getHistoryDetails[messageStore.getActiveFUuid].list"
           :class="item.from_uid==userInfoStore.getUserInfo.value.uuid?'item-right':''">
        <div class="avatar" v-if="item.from_uid != userInfoStore.getUserInfo.value.uuid">
          <img src="@/assets/images/avatar.jpg" alt="">
        </div>
        <div class="info">
          <!--<div class="nickname">ganganlee</div>-->
          <div class="content">{{ item.msg_content }}</div>
        </div>
        <div class="avatar" v-if="item.from_uid == userInfoStore.getUserInfo.value.uuid">
          <img src="@/assets/images/avatar.jpg" alt="">
        </div>
      </div>
    </div>
    <div class="msg-input-wrapper">
      <div class="tools-wrapper">
        <i class="iconfont chat-smile" data-prevent="y" @click="iconsStatusStore.changeStatus()" title="表情"></i>
        <i class="iconfont chat-folder" title="发送文件"></i>
        <i class="iconfont chat-message" title="聊天记录"></i>
        <Icons v-if="iconsStatusStore.status" ref="iconsRef"/>
      </div>
      <textarea class="input-wrapper" v-model="messageContent" @keyup.enter="send"></textarea>
      <div class="send-wrapper">
        <div class="btn" @click="send">发送</div>
      </div>
    </div>
  </div>
  </div>
  <addFriend v-if="friendModelStatus"
             :changeFriendStatus="changeFriendStatus"
             ref="addFriendRef"/>
</template>

<script setup lang="ts">
import addFriend from '@/components/addFriend/addFriend.vue';

import Icons from "@/components/message/icons.vue";

import {Add} from '@/hooks/addFriendHooks/add.ts';
import {useIconsStatusStore} from '@/stores/iconsStatus.ts';
import {friendListManage} from "@/hooks/friendListHooks/friendList.ts";
import {formatDate} from '@/utils/timeUtils';
import {useUserInfoStore} from '@/stores/userInfo.ts';
import {storeToRefs} from "pinia";
import {nextTick, onMounted, ref, watch} from "vue"
import {ElMessage} from "element-plus";
import {useWebSocket} from '@/hooks/websocket/useWebScoket';
import {useMessageStore} from '@/stores/message.ts';

//详情展示的dom
const detailsRef = ref(null);

//socket连接
let {connect, sendMessage} = useWebSocket();


//添加好友状态
let {friendModelStatus, changeFriendStatus, addFriendRef} = Add();
let iconsStatusStore = useIconsStatusStore();

//获取好友列表
//好友列表
let {friendListObj} = friendListManage();

const messageStore = useMessageStore();
onMounted(() => {
  //连接socket
  connect().then(()=>{
    //将websocket方法加入到全局变量中
    messageStore.setSendFunc(sendMessage);

    //加载聊天列表
    messageStore.setHistoryList();
  });
})

//监听新消息状态，有新消息时，自动滚动到底部
watch(() => messageStore.newMsgStatus, (val) => {
  nextTick(() => {
    detailsRef.value.scrollTop = detailsRef.value.scrollHeight;
  });
})

//监听消息容器滚动，滚动到顶部加载下一页数据
const loadPageStatus = ref(false);
const handleScroll = () => {
  const element = detailsRef.value;
  if (element) {
    const {scrollTop} = element;
    if (!loadPageStatus.value && scrollTop < 10) {
      //加载分页数据
      loadPageStatus.value = true;
      const obj = messageStore.getHistoryDetails[messageStore.getActiveFUuid];
      if (!obj.LoadAll) {
        //加载数据
        messageStore.setHistoryDetails(messageStore.getActiveFUuid);
      }
      setTimeout(() => {
        loadPageStatus.value = false;
      }, 500)
    }
  }
};

//获取用户信息
const userInfoStore = storeToRefs(useUserInfoStore());

//聊天消息
const messageContent = ref("")

//发送消息
function send() {
  let content = messageContent.value.trim();
  if (!content) {
    ElMessage.warning('请输入聊天内容');
    return;
  }

  //组织发送的消息
  let obj = {
    to_uid: messageStore.getActiveFUuid,
    msg_type: 'text',
    msg_content: content
  };
  let message = {
    "type": "chatMsg",
    "content": JSON.stringify(obj)
  }
  sendMessage(JSON.stringify(message)).then(() => {
    //添加消息到聊天列表中
    messageStore.addHistoryMsg(obj.to_uid, {
      created_at: formatDate('Y/m/d/H/i/s'),
      from_uid: userInfoStore.getUserInfo.value.uuid,
      msg_content: obj.msg_content,
      msg_type: "text",
      to_uid: obj.to_uid
    });
    messageContent.value = '';
    messageStore.changeHistoryMsgView(obj.to_uid, obj.msg_content);
  }).catch((err) => {
    console.log('1111');
    ElMessage.warning(err);
  });
}


</script>



<style scoped lang="scss">

.continue{
  display: flex;
  width: 100%;
  height: 100%;
}
.left-panel {
  width: 240px;
  background: #eee;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ccc;

  .search-wrapper {
    padding: 18px 8px 8px;
    background: #ddd;
    display: flex;

    .iconfont {
      font-size: 16px;
    }

    .input-wrapper {
      display: flex;
      flex: 1;
      margin-right: 8px;
      align-items: center;
      height: 24px;
      padding: 0 4px;
      border-radius: 4px;

      input {
        border: none;
        outline: none;
      }

      background: #fff;
    }

    .add-wrapper {
      background: #fff;
      width: 24px;
      height: 24px;
      border-radius: 4px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }

  .message-wrapper {
    display: flex;
    flex: 1;
    flex-direction: column;

    .message-item {
      display: flex;
      padding: 8px;
      width: 100%;
      cursor: pointer;

      .avatar {
        width: 40px;
        margin-right: 8px;
        font-size: 0;
        position: relative;

        .img-wrapper {
          width: 40px;
          height: 40px;
          border-radius: 4px;
          overflow: hidden;

          img {
            width: 100%;
            object-fit: cover;
          }
        }

        .unread-wrapper {
          position: absolute;
          top: -5px;
          right: -5px;
          width: 18px;
          height: 18px;
          border-radius: 10px;
          font-size: 12px;
          background: red;
          color: #fff;
          text-align: center;
          line-height: 18px;
        }
      }

      .content {
        display: flex;
        flex: 1;
        flex-direction: column;
        justify-content: space-between;

        .head {
          display: flex;
          justify-content: space-between;
          font-size: 14px;

          .nickname {
            flex: 1;
            margin-right: 8px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .time {
            font-size: 12px;
            color: #999;
          }
        }

        .footer {
          font-size: 12px;
          color: #999;
        }
      }
    }
    .message-item:hover{
      background: #e1e1e1;
    }

    .active {
      background: #ccc;
    }
  }
}

.right-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #eee;
  .head-wrapper{
    height: 50px;
    background: #ddd;
    padding: 0 4px 0 20px;
    display: flex;
    justify-content: space-between;
    .nickname{
      font-size: 20px;
      line-height: 50px;
    }
    .tools{
      display: flex;
      flex-direction: column;
      padding: 4px;
      .menu-list{
        display: flex;
        column-gap: 8px;
        .iconfont{
          font-size: 12px;
          cursor: pointer;
        }
      }
      .more{
        text-align: right;
        .iconfont{
          font-size: 20px;
          font-weight: bold;
        }
      }
    }
  }

  .msg-content-wrapper {
    flex: 1;
    padding: 8px 16px;
    gap: 8px;
    display: flex;
    flex-direction: column;
    overflow: auto;

    .item {
      display: flex;

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 2px;
        margin-right: 8px;

        img {
          width: 100%;
        }
      }

      .info {
        display: flex;
        flex-direction: column;

        .nickname {
          font-size: 12px;
          //line-height: 16px;
          margin-bottom: 6px;
        }

        .content {
          position: relative;
          background: #fff;
          padding: 8px;
          border-radius: 4px;
          width: 100%;
          white-space: pre-wrap;
          word-break: break-all;
          line-height: 20px;
        }

        .content::before {
          position: absolute;
          top: 10px;
          left: -5px;
          width: 10px;
          height: 10px;
          content: '';
          background: #fff;
          transform: rotate(45deg);
        }
      }
    }

    .item-right {
      justify-content: right;

      .info {
        align-items: end;
        margin-right: 8px;
        max-width: 80%;

        .content::before {
          left: unset;
          right: -5px;
        }
      }
    }
  }

  .msg-input-wrapper {
    padding: 8px 16px;
    border-top: 1px solid #ccc;

    .tools-wrapper {
      display: flex;
      gap: 12px;
      line-height: 20px;
      color: #777;
      position: relative;

      .iconfont {
        font-size: 20px;
        cursor: pointer;
      }
    }

    .input-wrapper {
      height: 48px;
      width: 100%;
      border: none;
      background: none;
      resize: none;
      font-size: 16px;
      line-height: 24px;
      overflow: auto;
    }

    .input-wrapper:focus {
      outline: none;
    }

    .send-wrapper {
      display: flex;
      justify-content: right;

      .btn {
        padding: 0 24px;
        background: #F3F4F5;
        width: auto;
        line-height: 32px;
        border-radius: 4px;
        color: #669900;
        cursor: pointer;
      }
    }
  }
}
</style>